package dev.xesam.androidkit.utils;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.TrafficStats;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import static android.net.TrafficStats.getUidRxBytes;
import static android.net.TrafficStats.getUidTxBytes;

/**
 * Created by Wom on 2015/7/9.
 * </p>
 * 调用进程需含有Looper
 * </p>
 * 设置时间参数单位为秒，log打印的统计时间单位为分钟
 * </p>
 * 未考虑内存溢出问题
 */
class TrafficCount {

    class MyHandler extends Handler {

        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Bundle b = msg.getData();
            long expendTraffic = b.getLong("sumTraffic");
            int expendTime = b.getInt("sumTime");
            onGetExpendTraffic(expendTraffic, expendTime);
        }
    }

    class MyRunable implements Runnable {
        MyHandler myHandlerInRun;
        int timeInRun;
        long formerTrafficInRun;
        String formerTimeInRun;

        MyRunable(MyHandler myHandler, int time, long formerTraffic, String formerTime) {
            myHandlerInRun = myHandler;
            timeInRun = time;
            formerTrafficInRun = formerTraffic;
            formerTimeInRun = formerTime;
        }

        @Override
        public void run() {
            Message msg = new Message();
            Bundle b = new Bundle();
            long latterTrafficInRun = trafficRecord();
            String latterTimeInRun = timeRecord();
            Log.i("流量统计",latterTimeInRun);
            long expendTrafficInRun = latterTrafficInRun - formerTrafficInRun;
            int expendTimeInRun = minusTime(latterTimeInRun, formerTimeInRun);
            b.putLong("sumTraffic", expendTrafficInRun);
            b.putInt("sumTime", expendTimeInRun);
            msg.setData(b);
            myHandlerInRun.sendMessage(msg);
            myHandlerInRun.postDelayed(this, timeInRun);
        }
    }

    private Context context;
    private String packageName;
    private MyHandler handler;
    private MyRunable runnable;
    private int time;

    public TrafficCount(Context context, int time) {
        this.context = context;
        packageName = context.getPackageName();
        handler = new MyHandler();
        this.time = time;
    }

    public void start() {

        time = time * 1000;
        long formerTraffic = trafficRecord();
        String formerTime = timeRecord();
        Log.i("流量统计",formerTime);
        runnable = new MyRunable(handler, time, formerTraffic, formerTime);
        handler.postDelayed(runnable, time);
        Log.i("流量统计", "开始统计");
    }

    public void stop() {
        handler.removeCallbacks(runnable);
    }

    private String timeRecord() {

        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
        Date date = new Date();
        return sdf.format(date);

    }

    private long trafficRecord() {
        PackageManager pm = context.getPackageManager();
        try {
            ApplicationInfo ai = pm.getApplicationInfo(packageName, 0);
            long inTraffic = getUidRxBytes(ai.uid) == TrafficStats.UNSUPPORTED ? 0 : getUidRxBytes(ai.uid) / 1024;
            long outTraffic = getUidTxBytes(ai.uid) == TrafficStats.UNSUPPORTED ? 0 : getUidTxBytes(ai.uid) / 1024;
            Log.i("流量统计", Integer.toString(ai.uid));
            return inTraffic + outTraffic;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return 0;
        }
    }

    private int minusTime(String latterTimeInRun, String formerTimeInRun) {
        int mTime = Integer.parseInt(latterTimeInRun.substring(4, 5)) - Integer.parseInt(formerTimeInRun.substring(4, 5));
        int hTime = Integer.parseInt(latterTimeInRun.substring(1, 2)) - Integer.parseInt(formerTimeInRun.substring(1, 2));
        if (hTime > 0) {
            return mTime + hTime * 60;
        } else {
            return mTime;
        }
    }


    private void onGetExpendTraffic(Long expendTraffic, int expendTime) {
        Log.i("流量统计", "消耗的流量" + Long.toString(expendTraffic) + "，所用时间" + Integer.toString(expendTime));
    }

    public void interrupt() {
        handler.post(runnable);
        Log.i("流量统计", "中断统计");
    }

}
